<template>
  <div>
    <Row :gutter="10">
      <Col>
        <Card>
          <div class="live_wrapper clearfix" style="margin-top: 10px">
            <div class="flex-row" style="justify-content: space-between">
              <div class="flow">
                <Select v-model="filter.shop_id"
                        style="width: 210px;margin: 0 10px 10px 0"
                        filterable
                        label-in-value
                        @on-change="search"
                        placeholder="请选择门店">
                  <Option :value="0">全部门店</Option>
                  <Option :value="item.id" v-for="(item, index) in shop_list" :key="index">{{ item.name }}</Option>
                </Select>
                <Select v-model="filter.good_id"
                        style="width: 210px;margin: 0 10px 10px 0"
                        filterable
                        label-in-value
                        @on-change="search"
                        placeholder="请选择商品">
                  <Option :value="0">全部商品</Option>
                  <Option :value="item.id" v-for="(item, index) in goods_list" :key="index">{{ item.name }}</Option>
                </Select>
                <Select v-model="filter.state"
                        style="width: 210px;margin: 0 10px 10px 0"
                        filterable
                        label-in-value
                        @on-change="search"
                        placeholder="请选择预约状态">
                  <Option :value='-1'>全部</Option>
                  <Option :value='0'>待服务</Option>
                  <Option :value='1'>服务中</Option>
                  <Option :value='2'>服务成功</Option>
                </Select>
                <DatePicker type="daterange"
                            v-model="filter.created_at"
                            @on-change="search"
                            placement="bottom-end"
                            placeholder="选择时间区间"
                            style="width: 210px;margin: 0 10px 10px 0"></DatePicker>
                <Input v-model="filter.name"
                       @on-search="search"
                       search
                       enter-button="搜索"
                       placeholder="请输入客户姓名"
                       style="width: 210px;margin: 0 10px 10px 0" />
                <Input v-model="filter.phone"
                       @on-search="search"
                       search
                       enter-button="搜索"
                       placeholder="请输入手机号码"
                       style="width: 210px;margin: 0 10px 10px 0" />
              </div>
              <div>
                <Button type="primary"
                        @click.stop="exportData()"
                        style=" width: 80px;height: 34px;font-size: 14px; margin-left: 10px">导出
                </Button>
              </div>
            </div>
          </div>

          <p class="admin_title">全部预约</p>

          <Row class="margin-top-10 table_pattern table_pattern2">
            <Table style="width: calc(100vw - 256px - 36px - 32px)"
                   :loading="loading"
                   :columns="columns"
                   :data="list"></Table>
          </Row>
          <Row class="margin-top-10">
            <Page :total="pagenation.totalPage"
                  :page-size="pagenation.perPage"
                  :current="pagenation.currentPage"
                  show-elevator
                  show-total
                  @on-change="change"></Page>
          </Row>
        </Card>
      </Col>
    </Row>

    <Modal v-model="showDetailModal"
           title="预约详情"
           width="900px"
           :mask-closable="false"
           class="public_modal_header edit_modal">
      <div class="flex modal-detail">
        <div class="item"><span>门店:</span>{{ appointInfo.shop_name }}</div>
        <div class="item"><span>客户姓名:</span>{{ appointInfo.name }}</div>
        <div class="item"><span>客户电话:</span>{{ appointInfo.phone }}</div>
        <div class="item"><span>商品名称:</span>{{ appointInfo.good_name }}</div>
        <div class="item"><span>预约时间:</span>{{ appointInfo.created_time }}</div>
        <div class="item"><span>服务地址:</span>{{ appointInfo.service_address }}</div>
        <div class="item" v-if="appointInfo.service_start_at_time">
          <span>服务开始时间:</span>{{ appointInfo.service_start_at_time }}
        </div>
        <div class="item" style="height: fit-content;align-items: normal" v-if="appointInfo.service_start_img">
          <span>服务开始照片：</span>
          <div style="display: flex;flex-flow: wrap;">
            <img v-for="item in appointInfo.startImgList" :src="item" alt="" style="margin: 0 5px 5px"
                 @click="handleView(item)" />
          </div>
        </div>

        <div class="item" v-if="appointInfo.service_finsh_time">
          <span>服务结束时间:</span>{{ appointInfo.service_finsh_time }}
        </div>
        <div class="item" style="height: fit-content;align-items: normal" v-if="appointInfo.service_finsh_img">
          <span>服务结束照片：</span>
          <div style="display: flex;flex-flow: wrap;">
            <img v-for="item in appointInfo.finishImgList" :src="item" alt="" style="margin: 0 5px 5px"
                 @click="handleView(item)" />
          </div>
        </div>

        <div class="item"><span>状态:</span>{{ appointInfo.state_name }}</div>
      </div>
    </Modal>

    <Modal v-model="showUpLoadModal"
           title="上传服务照片"
           width="40%"
           :mask-closable="false"
           class="public_modal_header edit_modal">
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="100"
            style="width: 90%;margin: 0 auto;padding: 25px 0 10px;">
        <FormItem label="服务照片" prop="img" class="label_required label_required2">
          <div class="clearfix live_cover">
            <div style="float: left;margin-right: 18px;">
              <template>
                <div class="demo-upload-list" v-for="(item,index) in imgList" style="margin: 5px">
                  <img :src="item" style='width:100px; height:100px;object-fit: cover;'>
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(index)"></Icon>
                  </div>
                </div>

                <div v-if="!imgList.length">
                  <div class="no_pic"><img src="../../assets/images/expo/pic2.png" alt="" width="24" /></div>
                </div>
              </template>
            </div>
            <Upload ref="upload"
                    multiple
                    :max-size="5120"
                    :show-upload-list="false"
                    action="https://up.qiniup.com"
                    :on-format-error="handleFormatError"
                    :on-progress="handleProgress"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    :format="['jpg', 'png', 'jpeg']"
                    :data="{token:upload_token}"
                    :before-upload="handleBeforeUpload"
                    style="float: left;">
              <Button
                  style="width:80px;height:30px;background:rgba(248,249,250,1);border:1px solid rgba(232,233,237,1);border-radius:2px;">
                上传文件
              </Button>
              <p style="color:#999;margin-top: 8px;">建议尺寸: 400*400px，JPG、PNG格式，图片不超过5M</p>
            </Upload>
          </div>
        </FormItem>
      </Form>
      <div class="btns">
        <Button :loading="isSubmitting" type="primary" @click="handleSubmit">提交</Button>
      </div>
    </Modal>

    <Modal title="查看图片" v-model="visible">
      <img :src="imgName" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>

import {
  getQiniu,
  childBtnPermission,
  goodsListForSelect,
  shopForSelect,
  customerAppointmentList,
  changeAppointmentServiceState,
} from '@/api/main'
import Time from '@/tool/Time'

export default {
  name: 'appointment-list',
  data () {
    return {
      permissionList: [],
      isSubmitting: false,
      pagenation: {},
      columns: [
        {
          title: '门店名称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.shop_name)
          },
        },
        {
          title: '商品名称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.good_name)
          },
        },
        {
          key: 'customer_name',
          title: '客户姓名',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.customer_name)
          },
        },
        {
          title: '手机号码',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.phone)
          },
        },
        {
          title: '服务地址',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.service_address)
          },
        },
        {
          title: '状态',
          align: 'center',
          render: (h, params) => {
            let color = '#333333'
            switch (params.row.state) {
              case 0: // 待服务
                color = '#D40303'
                break;
              case 1: // 服务中
                color = '#07BD21'
                break;
              case 2: // 服务成功
                color = '#2B76EE'
                break;
              default:
                break;
            }
            return h('strong', { style: { color } }, params.row.state_name)
          },
        },
        {
          title: '创建时间',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.created_time)
          },
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                  'Button',
                  {
                    style: {
                      margin: '0 5px 5px 0',
                      border: 0,
                      background: 'transparent',
                      fontSize: '14px',
                      color: '#377EEF',
                      display: this.permissionList.indexOf('appoint-info') !== -1 ? 'inline-block' : 'none'
                    },
                    on: {
                      click: () => {
                        let appointInfo = Object.assign({}, params.row)
                        if (appointInfo.service_start_img) {
                          appointInfo.startImgList = appointInfo.service_start_img.split(',')
                        }

                        if (appointInfo.service_finsh_img) {
                          appointInfo.finishImgList = appointInfo.service_finsh_img.split(',')
                        }

                        this.appointInfo = appointInfo

                        this.showDetailModal = true
                      },
                    },
                  },
                  '详情',
              ),
              h(
                  'Button',
                  {
                    style: {
                      margin: '0 5px 5px 0',
                      border: 0,
                      background: 'transparent',
                      fontSize: '14px',
                      color: '#377EEF',
                      display: this.permissionList.indexOf('appoint-state') !== -1 && (params.row.state == 0 || params.row.state == 1) ? 'inline-block' : 'none'
                    },
                    on: {
                      click: () => {
                        this.formValidate.id = params.row.id
                        this.formValidate.state = params.row.state == 0 ? 1 : 2 //状态(0：待服务 1：服务中 2：服务成功)
                        this.formValidate.img = ''
                        this.showUpLoadModal = true
                      },
                    },
                  },
                  params.row.state == 1 ? '服务完成' : '服务开始',
              ),
            ])
          },
        },
      ],
      list: [],
      loading: true,
      showUpLoadModal: false,
      upload_token: '',
      visible: false,
      imgName: '',
      formValidate: {
        id: 0,
        state: 0,
        img: '',
      },
      imgList: [],
      filter: {
        page: 0,
        page_size: 20,
        shop_id: 0,
        good_id: 0,
        state: -1, // 状态(0：待服务 1：服务中 2：服务成功)
        name: '',
        phone: '',
        date_range: '',
        created_at: ['', ''],
      },
      goods_list: [],
      shop_list: [],
      showDetailModal: false,
      appointInfo: {},
    }
  },
  watch: {
    'filter.created_at': function () {
      let created_at_start = Time.dateToTimestamp(this.filter.created_at[0])
      let created_at_end = Time.dateToTimestamp(this.filter.created_at[1])
      if (created_at_start !== 0 && created_at_end !== 0) {
        this.filter.date_range = created_at_start + '-' + created_at_end
      } else {
        this.filter.date_range = ''
      }
    },
  },
  methods: {
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getList()
    },
    search: function () {
      this.filter.page = 0
      this.getList()
    },
    handleBeforeUpload (file) {
      if (file.size > 5 * 1024 * 1024) {
        this.$Message.error("图片不超过5M")
      }
    },
    handleSubmit () {
      if (!this.imgList.length) {
        this.$Message.error("请上传服务照片");
        return;
      }
      this.formValidate.img = this.imgList.join(',')

      //console.log(this.formValidate); return false;

      if (this.isSubmitting) return
      this.isSubmitting = true

      changeAppointmentServiceState(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.showUpLoadModal = false
          this.search()
        } else {
          this.$Message.error(res.text)
        }
        setTimeout(() => this.isSubmitting = false, 1000)
      })
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.imgList.push(file.response.domain + file.response.key)
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove (index) {
      this.imgList.splice(index, 1)
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    exportData () {
      let _this = this
      _this.filter.page = 0
      _this.filter.page_size = 500
      _this.export_list = []
      _this.export()
    },
    export () {
      let _this = this
      customerAppointmentList(this.filter).then(res => {
        if (res.code == 0) {
          if (res.data.length) {
            _this.export_list.push.apply(_this.export_list, res.data)
            _this.filter.page++
            setTimeout(() => {
              _this.export()
            }, 500)
          } else {
            _this.filter.page_size = 20
            const { export_json_to_excel } = require('../../excel/Export2Excel');
            const tHeader = ['客户姓名', '手机号码'];
            const filterVal = ['customer_name', 'good_name'];
            const data = _this.formatJson(filterVal, _this.export_list)
            export_json_to_excel(tHeader, data, '客户预约列表')
          }
        }
      })
    },
    async initQn () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
    },
    getPermissionList (parent_name) {
      childBtnPermission({ parent_name }).then(res => {
        if (res.code === 0) {
          this.permissionList = res.data
        }
      })
    },
    getList () {
      customerAppointmentList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
  },
  mounted () {
    this.initQn();
    this.getPermissionList('appointment-list')
    this.getList()

    goodsListForSelect().then(res => {
      if (res.code === 0) {
        this.goods_list = res.data || []
      }
    })

    shopForSelect().then(res => {
      if (res.code === 0) {
        this.shop_list = res.data || []
      }
    })
  }
}
</script>
<style>
</style>
<style scoped lang="less">
.modal-detail {
  padding: 40px 5%;

  .title {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    color: #333333;
  }

  .item {
    margin-left: 30px;
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    font-size: 14px;
    color: #666666;

    span {
      width: 140px;
      flex-shrink: 0;
    }

    img {
      width: 120px;
      height: 120px;
    }
  }
}
</style>
